package org.ciallo.simplemusicplayer.util;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.text.TextUtils;
import org.ciallo.simplemusicplayer.data.model.Song;
import timber.log.Timber;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: MediaStore 工具类，用于从设备媒体库加载歌曲信息
 * @Package: org.ciallo.simplemusicplayer.util
 * @Project: SimpleMusicPlayer
 * @name: MediaStoreUtil
 * @Date: 2025/5/30-04:33
 * @Filename: MediaStoreUtil
 */
public class MediaStoreUtil {

    /**
     * 从 MediaStore 加载所有音频文件信息。
     *
     * @param context Context.
     * @return 包含所有扫描到的歌曲的列表；如果发生错误或没有权限，则返回空列表。
     */
    public static List<Song> loadSongsFromMediaStore(Context context) {
        List<Song> songs = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();

        // 定义查询URI，Android Q (API 29) 及以上版本推荐使用 getVolumeName
        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        // 定义要查询的列 (Projection)
        String[] projection = {
                MediaStore.Audio.Media._ID,                 // 歌曲ID (long)
                MediaStore.Audio.Media.TITLE,               // 歌曲标题 (String)
                MediaStore.Audio.Media.ARTIST,              // 歌手名称 (String)
                MediaStore.Audio.Media.ARTIST_ID,           // 歌手ID (long) - 用于可能的关联
                MediaStore.Audio.Media.ALBUM,               // 专辑名称 (String)
                MediaStore.Audio.Media.ALBUM_ID,            // 专辑ID (long) - 用于可能的关联和封面获取
                MediaStore.Audio.Media.DATA,                // 文件路径 (String) - 非常重要
                MediaStore.Audio.Media.DURATION,            // 时长 (long, in milliseconds)
                MediaStore.Audio.Media.DATE_ADDED,          // 添加日期 (long, in seconds since epoch)
                MediaStore.Audio.Media.TRACK,               // 音轨号 (int, e.g., 1001 for CD1 Track 1)
                MediaStore.Audio.Media.YEAR,                // 发行年份 (int)
                MediaStore.Audio.Media.SIZE,                // 文件大小 (long, in bytes)
                MediaStore.Audio.Media.MIME_TYPE            // MIME类型 (String, e.g., "audio/mpeg")
        };

        // 筛选条件: 必须是音乐文件 (is_music != 0)，并且可以添加时长或其他过滤条件
        // 例如：只加载时长大于60秒的歌曲 MediaStore.Audio.Media.DURATION + " >= 60000"
        String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
        String[] selectionArgs = null;

        // 排序方式，例如按标题升序
        String sortOrder = MediaStore.Audio.Media.TITLE_KEY + " ASC";
        // 或者 String sortOrder = MediaStore.Audio.Media.DATE_ADDED + " DESC"; // 按添加日期降序

        Cursor cursor = null;
        try {
            cursor = contentResolver.query(
                    collection,
                    projection,
                    selection,
                    selectionArgs,
                    sortOrder
            );

            if (cursor != null && cursor.moveToFirst()) {
                // 获取各列的索引
                int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID);
                int titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE);
                int artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST);
                int artistIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST_ID);
                int albumColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
                int albumIdColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
                int dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
                int durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION);
                int dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATE_ADDED);
                int trackColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TRACK);
                int yearColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.YEAR);
                int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE);
                int mimeTypeColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.MIME_TYPE);

                do {
                    long id = cursor.getLong(idColumn);
                    String title = cursor.getString(titleColumn);
                    String artist = cursor.getString(artistColumn);
                    long artistId = cursor.getLong(artistIdColumn);
                    String album = cursor.getString(albumColumn);
                    long albumId = cursor.getLong(albumIdColumn);
                    String path = cursor.getString(dataColumn);
                    long duration = cursor.getLong(durationColumn);
                    long dateAddedSeconds = cursor.getLong(dateAddedColumn);
                    int track = cursor.getInt(trackColumn); // 原始音轨号，可能是 X0Y 格式
                    int year = cursor.getInt(yearColumn);
                    long size = cursor.getLong(sizeColumn);
                    String mimeType = cursor.getString(mimeTypeColumn);

                    // 文件可能已被删除，但 MediaStore 仍有记录，进行简单校验
                    if (path == null || !new File(path).exists()) {
                        Timber.w("Song path invalid or file does not exist, skipping: %s", path);
                        continue;
                    }

                    // 处理音轨号 (通常 X0Y 表示第X张CD的第Y首，我们只取Y)
                    int trackNumber = track % 1000;
                    int discNumber = track / 1000;

                    // 获取专辑封面URI
                    Uri albumArtContentUri = ContentUris.withAppendedId(Uri.parse("content://media/external/audio/albumart"), albumId);
                    String albumArtUriString = (albumArtContentUri != null) ? albumArtContentUri.toString() : null;

                    // 获取文件夹路径
                    String folderPath = "";
                    File songFile = new File(path);
                    File parentDir = songFile.getParentFile();
                    if (parentDir != null) {
                        folderPath = parentDir.getAbsolutePath();
                    }

                    // 创建 Song 对象
                    Song song = new Song();
                    song.setId(id);
                    song.setTitle(TextUtils.isEmpty(title) ? songFile.getName() : title);
                    song.setArtistName(TextUtils.isEmpty(artist) ? Constants.UNKNOWN_STRING : artist);
                    song.setArtistIdRoom(artistId); // 使用 Room Entity 对应的字段名
                    song.setAlbumName(TextUtils.isEmpty(album) ? Constants.UNKNOWN_STRING : album);
                    song.setAlbumIdRoom(albumId);   // 使用 Room Entity 对应的字段名
                    song.setPath(path);
                    song.setDuration(duration);
                    song.setAlbumArtUri(albumArtUriString);
                    song.setFolderPath(folderPath);
                    song.setDateAdded(dateAddedSeconds * 1000); // 转换为毫秒
                    song.setTrackNumber(trackNumber);
                    song.setYear(year);
                    song.setSize(size);
                    song.setMimeType(mimeType);
                    // titlePinyin 等字段需要在 Repository 或 ViewModel 中使用 PinyinUtil 生成并填充

                    songs.add(song);

                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            Timber.e(e, "Error querying MediaStore for songs.");
            // 可以返回空列表或抛出异常，具体取决于错误处理策略
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        Timber.i("Loaded %d songs from MediaStore.", songs.size());
        return songs;
    }

    // 同样，可以添加 loadAlbumsFromMediaStore 和 loadArtistsFromMediaStore 方法，
    // 如果你也打算将 Album 和 Artist 作为 Room 实体并从 MediaStore 加载。
    // 但为了先完成单曲列表，我们暂时只关注 loadSongsFromMediaStore。
}
